var selectedRow='';
var vueObje = new Vue({
    el:'#vueObj',
    data:{searchobj:searchobj},
    computed: {
        roleName: function () {
            if(this.searchobj.roleName == '' || this.searchobj.roleName == null){
                return '';
            }else{
                return this.searchobj.roleName;
            }
        }
    }
});
$(function () {
    initTextSearch("#roleName",
        basePath + 'pfUser/searchRoleList?t='+new Date().getTime()+'&roleName=',
        ['id', 'roleName'],
        {'id':'角色Id', 'roleName':'角色名称'},
        'id',
        'roleName',
        true,
        selectRoleValue,
        noSelectRoleValue,
        false);

    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openEditPage('info');
        },
        'click .mod': function(e, value, row, index) {
            //编辑操作
            selectedRow=row;
            openEditPage('edit');
        },
        'click .delete' : function(e, value, row, index) {
            //删除操作
            selectedRow=row;
            deleteUser();
        },
        'click .statusSet': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            changeState();
        },
        'click .creator': function(e, value, row, index) {
             console.log(value);
        },
        'click .operator': function(e, value, row, index) {
            console.log(value);
        },
        'click .isvInfoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openCommonIsvPage(row.isvPid, 'doc');
        },
    }
});


function selectRoleValue(data) {
    if (!data || !data.id) {
        return;
    }
    $('#roleId').val(data.id);
    doRefresh();
}

function noSelectRoleValue() {
    $('#roleId').val('');
}


function actionFormatter(value, row, index) {
    return '<a class="mod" >编辑</a> ' + getSeparator() + '<a class="statusSet" >' + (row.status=='normal'?'冻结':'恢复') + '</a> ' + getSeparator() +  '<a class="delete">删除</a>';
}

function formatStatus(value, row, index){
    return convertMapCodeText(freezeStatusEnumMap,value);
}
function formatUserType(value, row, index){
    return convertMapCodeText(userTypeEnumMap,value);
}
function formatRoleId(value, row, index){
    if(row.roleList.length > 1){
        var str = new Array();
            for(var index in row.roleList){
                str.push(row.roleList[index].roleName);
            }
        return "<a href=\"#\" title=\"" +str.join(",")+"\">"+row.roleList[0].roleName+",...</a>";
    }else if(row.roleList.length == 1){
        return "<a href=\"#\" title=\"" + row.roleList[0].roleName+"\">"+row.roleList[0].roleName+"</a>";;
    }else{
        return "";
    }
}

function formatCompany(value, row, index){
    return convertListCodeText(companyList,value,'enumValue','enumTxt');
}

function openEditPage(command) {
    if (command != 'add' && command != 'edit'&&command != 'info') return;
    var id="";
    if (command != 'add') {
        if (!selectedRow || selectedRow.id == '') {
            toastr.error(common_no_choose_msg.format("操作"));
            return;
        }
        id=selectedRow.id;
    }
    var tableOptions = $('#dataTable').bootstrapTable('getOptions', null);
    var searchStr = $("#searchForm").serialize()+ '&pageNo=' + tableOptions.pageNumber + '&pageSize=' + tableOptions.pageSize;
    console.log(searchStr.replace(/&/g,","));
    window.location.href = basePath + "pfUser/editPfUserPage?type=" + command + "&id=" + id +"&searchStr="+searchStr.replace(/&/g,",");
}
function doReset() {
    clearFrom('searchForm');
    $("#searchKey").attr("name", 'userName');
    $("#searchKey").attr("placeholder", "输入账号");
}
function doRefresh() {
    selectedRow = '';
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'pfUser/getGridData?t='+new Date().getTime()
    });
}
function changeState() {
    if (!selectedRow.status) {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    var status =  (selectedRow.status == 'freeze') ?'enabled':'freeze';
    var postData = {
        idList: [selectedRow.id],
        status: status
    };
    doStateChange(postData,((selectedRow.status == 'freeze') ?'恢复':'冻结')+'成功');
}

function deleteUser() {
    if (!selectedRow.id) {
        toastr.error(common_no_choose_msg.format("删除"));
        return;
    }
    swal({
        title:"",
        text:'[' + selectedRow.userName + ']当前处于[' + convertMapCodeText(freezeStatusEnumMap,selectedRow.status)+ ']状态，确认删除？',
        type:"warning",
        showCancelButton:"true",
        showConfirmButton:"true",
        confirmButtonText:"确定",
        cancelButtonText:"取消",
        animation:"slide-from-top"
    }, function() {
        var postData = {
            idList: [selectedRow.id],
            status: 'delete'
        };
        doStateChange(postData,"删除成功");
    });
}
function batchUpdate(cmd){
    var users=getSelectedRows('#dataTable');
    if(!users||users.length<1){
        toastr.error('请先选择要操作的用户！');
        return;
    }
    var sum=users.length;
    var idList=new Array();
    switch(cmd)
    {
        case 'freeze':
            for(var i=0;i<users.length;i++){
                if (!users[i].status||users[i].status=='freeze') {
                    users.splice(i,1);//已冻结的内容
                    i--;
                }else{
                    idList.push(users[i].id);
                }
            }
            if(users.length==0){
                toastr.error('选中的账户都已冻结，无须再冻结！');
                return;
            }
            var postData = {
                idList: idList,
                status: 'freeze'
            };
            doStateChange(postData,"选中"+sum+"条数据，成功冻结"+idList.length+"条数据");
            break;
        case 'revoke':
            for(var i=0;i<users.length;i++){
                if (!users[i].status||users[i].status=='normal') {
                    users.splice(i,1);//正常的内容
                    i--;
                }else{
                    idList.push(users[i].id);
                }
            }
            if(users.length==0){
                toastr.error('选中的账户都正常，无须再恢复！');
                return;
            }
            var postData = {
                idList: idList,
                status: 'normal'
            };
            doStateChange(postData,"选中"+sum+"条数据，成功恢复"+idList.length+"条数据");
            break;
        case 'del':
            for(var i=0;i<users.length;i++){
                idList.push(users[i].id);
            }
            swal({
                title:"",
                text:'已选中'+idList.length+'条数据，这些数据删除后将无法恢复，确认删除?',
                type:"warning",
                showCancelButton:"true",
                showConfirmButton:"true",
                confirmButtonText:"确定",
                cancelButtonText:"取消",
                animation:"slide-from-top"
            }, function() {
                var postData = {
                    idList:idList,
                    status:'delete'
                };
                doStateChange(postData,'批量删除成功'+idList.length+'条数据');
            });
            break;
        default:
    }
}
function doStateChange(postData,msg) {
    $.ajax({
        type: 'post',
        url: basePath + 'pfUser/changeState',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success: function (data) {
            if (data && data.isSuccess) {
                toastr.success(msg);
                doRefresh();
            } else if (data && !data.isSuccess) {
                toastr.error(data.errorDesc?data.errorDesc:'数据操作失败');
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


// dataTable
$('#dataTable').on("click-row.bs.table", function (e, row, $element) {
    // checkBox 的勾选
    // var index = $element[0].rowIndex - 1;
    // $('#dataTable').bootstrapTable('uncheckAll');
    // $('#dataTable').bootstrapTable('check', index);
    $('#dataTable .success').removeClass('success');//去除之前选中的行的，选中样式
    $element.addClass('success');//添加当前选中的 success样式用于区别
    changeStatueBtn(row.status == 'enabled',"冻结","恢复");
    selectedRow = row;
});

// 双击bootstraptable一行的事件
// $('#dataTable').on("dbl-click-row.bs.table", function (e, row, $element) {
//      console.log('双击');
// });



function changeSearch() {
        var selectType =  $("#selectType").val();
        switch (selectType){
            case 'userName':
            {
                $("#searchKey").attr("name",selectType);
                $("#searchKey").attr("placeholder","输入账号");
                break;
            };
            case 'telephone':
            {
                $("#searchKey").attr("name",selectType);
                $("#searchKey").attr("placeholder","输入手机号");
                break;
            };
            case 'realName':
            {
                $("#searchKey").attr("name",selectType);
                $("#searchKey").attr("placeholder","输入姓名");
                break;
            };
        }
}


//获取参数转换为后台接受参数-通用
var isInit = true;
function getParams(params) {
    var temp = $("#searchForm").serializeJsonObject();
    if(isInit){
        isInit = false;
        temp["pageSize"]=searchobj.pageSize?searchobj.pageSize:params.pageSize;
        temp["pageNo"]=searchobj.pageNo?searchobj.pageNo:params.pageNumber;
    }else{
        temp["pageSize"]=params.pageSize;
        temp["pageNo"]=params.pageNumber;
    }
    return temp;
}


